package com.loren.demo32.interceptor;

import com.loren.demo32.tenant.CustomTenantResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
public class TenantIdInterceptor implements HandlerInterceptor {

    private final CustomTenantResolver customTenantResolver;

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        this.customTenantResolver.setCurrentTenant(request.getHeader("x-tenant-id"));
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        this.customTenantResolver.removeCurrentTenant();
    }
}
